<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Elsearch;

class ESInit extends Command
{
    public $_client = null;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'es:init';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'init elsearch db';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->_client = \Elasticsearch\ClientBuilder::create()->build();  
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // $rs = $this->get_index('search_dangerous');
        // print_rf($rs);
        // die();
        $this->del_index('search_dangerous');
        $this->init_dangerous_keywords_index();
        $ElsearchModal = new Elsearch();
        $ElsearchModal->rebuild_search_dangerous();
    }
    public function init_dangerous_keywords_index(){
        if($this->check_index('search_dangerous') == true){
            return;
        }
        $params = [ 'index' => 'search_dangerous', //索引名（相当于mysql的数据库） 
                    'body' => [ 'mappings' => 
                        [ 'dangerous_keywords' => 
                        [ '_all'=>[ 'enabled' => 'false' ], 
                            'properties' => [
                            'index_id' => [ 'type' => 'integer'],
                            'dangerous_id' => [ 'type' => 'text'],
                            'keywords' => [ 'type' => 'text' ], 
                            'name' => [ 'type' => 'keyword' ], 
                            ]
                        ] ] ] ];
        $data = $this->_client->indices()->create($params);
    }
    public function del_index($index){
        $params = [
            'index' => $index,  //索引名（相当于mysql的数据库）
        ];
        $this->_client->indices()->delete($params);
    }
    public function check_index($index){
        $params = [
                'index' => $index,
                'client' => [
                    'ignore' => 404
                ]
            ];
        $res = $this->_client->indices()->getSettings($params);
        if(isset($res['error'])){
            return false;
        }else{
            return true;
        }
    }
    public function get_index($index){
        $params = [
                'index' => $index,
                'client' => [
                    'ignore' => 404
                ]
            ];
        return $res = $this->_client->indices()->getSettings($params);
    }
}
